<template>
  <CustomTableCard 
    footer
    :temporary="temporary"
    actions
    :total="total" 
    :page.sync="queryParams.page" 
    :limit.sync="queryParams.limit" 
    :width="baseInfo.id ? 600 : 1280"
    :showDrawer.sync="showDrawer" 
    ok-text="发布"
    @on-page="getList" 
    @cancel="handleCancel"
    @ok="handleOk"
    :title="baseInfo.id ? $t('actions.edit') : $t('actions.add')">
    <template v-slot:header>
      <v-row>
        <v-col cols="2">
          <!-- <v-select
            v-model="queryParams.type"
            :items="['跟团游', '自由行']"
            label="按团期类型搜索"
            solo
            dense
            outlined
            flat
            hide-details
            clearable
          ></v-select> -->
          <dict-select
            v-model="queryParams.type"
            type="infotag"
            outlined
            hide-details
            clearable
            dense
            label="选择信息类型"
            @change="getList(1)"/>
        </v-col>
        <v-col cols="2">
          <v-select
            v-model="queryParams.dateType"
            :items="['创建时间', '出团时间']"
            solo
            dense
            outlined
            flat
            hide-details
          ></v-select>
        </v-col>
        <v-col cols="3">
          <date-picker v-model="queryParams.dateRange"></date-picker>
        </v-col>
        <v-col cols="2">
          <v-text-field
            label="搜索线路"
            outlined
            dense
            hide-details
          ></v-text-field>
        </v-col>
        <v-col>
          <v-btn color="info" class="mr-3" @click="getList(1)">{{ $t('actions.search') }}</v-btn>
        </v-col>
        <v-col cols="2" class="text-right">
          <v-btn color="primary" @click="showDrawer = true">{{ $t('actions.add') }}</v-btn>
        </v-col>
      </v-row>
    </template>
    <el-table
      v-loading="listLoading"
      v-auto-height
      :height="tableHeight"
      :data="tableData"
      stripe
      fit
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        type="selection"
        align="center"
        width="55">
      </el-table-column>
      <el-table-column
        prop="id"
        label="编号"
        width="60">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="foundation_prodcut_name"
        label="产品名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="info_type_name"
        label="信息类型"
        width="180">
      </el-table-column>
      <el-table-column
        prop="plan_date"
        label="接团日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="back_date"
        label="散团日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="remain_num"
        label="计划人数"
        width="180">
      </el-table-column>
      <el-table-column
        prop="plan_people"
        label="已收人数"
        width="180">
      </el-table-column>
      <el-table-column
        prop="remain_num"
        label="余位数"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="允许超员"
        width="140">
        <template v-slot:default='{ row }'>
          <span>{{row.remain_status == 1 ? '允许' : '不允许'}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="所属部门"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="所属员工"
        width="180">
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间"
        width="180">
      </el-table-column>
      <el-table-column
        prop="updated_at"
        label="更新时间"
        width="180">
      </el-table-column>
      <el-table-column
        fixed="right"
        prop="status"
        label="状态"
        width="140">
        <template slot-scope="{ row }">
          <v-switch class="mt-0" dense hide-details :input-value="row.status == 2" :label="row.status == 2 ? '已激活' : '已锁定'" @change="setStatus(row)"></v-switch>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="180">
        <template slot-scope="{ row }">
          <v-btn class="mr-2" small color="primary" :disabled="row.status != 2" outlined @click="$router.push({path: '/plan/fill-in', query: {id: row.id}})">录单</v-btn>
          <v-btn small color="info" outlined @click="handleEdit(row)">编辑</v-btn>
          <!-- <v-btn small color="warning" outlined @click="handleRmove(row)">{{ $t('actions.delete') }}</v-btn> -->
        </template>
      </el-table-column>
    </el-table>
    <template v-slot:actions>
      <div>
        <v-btn small color="warning" :disabled="!multipleSelection.length" class="mr-2" @click="handleRmove()">{{ $t('actions.delete') }}</v-btn>
        <v-btn small color="success" :disabled="!multipleSelection.length" class="mr-2" @click="setStatusAll(2)">{{ $t('actions.open') }}</v-btn>
        <v-btn small color="warning" :disabled="!multipleSelection.length" @click="setStatusAll(1)">{{ $t('actions.close') }}</v-btn>
      </div>
    </template>
    <template v-slot:drawer>
      <section class="pa-3">
        <v-form
          ref="form"
          :lazy-validation="false"
        >
          <v-row>
            <v-col v-if="!baseInfo.id">
              <calendar
                ref="calendar"
                style="width:700px;"
                :min-date="new Date()"
                :max-date="dayjs().add(3, 'month').format('YYYY-MM-DD')"
                @update:to-page="handleMonthChange"
              >
                <div slot="day-content" slot-scope="{ day }" :class="[{'checked': isChecked(day)}, gtToDay(day) ? 'calendar-body-item' : 'calendar-body-gray', {'disable': radioDateType === 2}]" @click="handleClickDate(day)">
                  <div>
                    <div class="calendar-body-item_date">{{ day.day }}</div>
                    <div>
                      <!-- <span style="color: #f94570;font-size: 12px;">{{day.date}}</span> -->
                    </div>
                  </div>
                </div>
              </calendar>
            </v-col>
            <v-col>
              <v-card>
                <v-card-title>
                  <small>基本信息</small>
                </v-card-title>
                <v-divider></v-divider>
                <div class="d-flex align-center px-3" v-if="!baseInfo.id">
                  <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>产品名称</label>
                  <v-text-field
                    v-model="baseInfo.foundation_prodcut_name"
                    placeholder="请选择"
                    readonly
                    :rules="[rules.required]"
                    required
                    @click="showSelectProduct = true"
                  ></v-text-field>
                </div>
                <div class="d-flex align-center px-3" v-if="baseInfo.id">
                  <label style="width: 140px" class="text-right pr-3">产品名称</label>
                  <v-text-field
                    v-model="baseInfo.foundation_prodcut_name"
                    placeholder="请选择"
                    readonly
                    disabled
                  ></v-text-field>
                </div>
                <div class="d-flex align-center px-3" v-if="!baseInfo.id">
                  <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>行程天数</label>
                  <v-text-field
                    v-model.number="baseInfo.day_num"
                    placeholder="请输入"
                    type="number"
                    clearable
                    :rules="[rules.required]"
                    required
                  ></v-text-field>
                </div>
                <div class="d-flex align-center px-3">
                  <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>计划位</label>
                  <v-text-field
                    v-model.number="baseInfo.remain_num"
                    placeholder="请输入"
                    type="number"
                    clearable
                    :rules="[rules.required]"
                    required
                  ></v-text-field>
                </div>
                <div class="d-flex align-center px-3" v-if="baseInfo.id">
                  <label style="width: 140px" class="text-right pr-3">接团日期</label>
                  <v-text-field
                    v-model.number="baseInfo.plan_date"
                    placeholder="请输入"
                    disabled
                  ></v-text-field>
                </div>
                <div class="d-flex align-center px-3" v-if="baseInfo.id">
                  <label style="width: 140px" class="text-right pr-3">散团日期</label>
                  <v-text-field
                    v-model.number="baseInfo.plan_date"
                    placeholder="请输入"
                    disabled
                  ></v-text-field>
                </div>
                <div class="d-flex align-center px-3">
                  <label style="width: 140px" class="text-right pr-3">允许超员</label>
                  <v-radio-group v-model="baseInfo.remain_status" row>
                    <v-radio label="是" :value="1"></v-radio>
                    <v-radio label="否" :value="2"></v-radio>
                  </v-radio-group>
                </div>
                <div class="d-flex align-center px-3" v-if="!baseInfo.id">
                  <label style="width: 140px" class="text-right pr-3">日期</label>
                  <v-radio-group v-model="radioDateType" column>
                    <v-radio label="从日历选择日期" :value="1"></v-radio>
                    <v-radio label="自定义时间段" :value="2"></v-radio>
                  </v-radio-group>
                </div>
                <div v-if="radioDateType == 2" class="d-flex align-center px-3">
                  <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>日期范围</label>
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    :picker-options="pickerOptions"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </div>
                <div v-if="radioDateType == 2" class="d-flex align-center px-3 my-4 pb-5">
                  <div style="width: 140px" class="text-right pr-3 flex-shrink-0"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>星期范围</div>
                  <div class="d-flex flex-wrap">
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周一" hide-details :value="1" required :rules="[rules.checkboxRules]"></v-checkbox>
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周二" hide-details :value="2" required :rules="[rules.checkboxRules]"></v-checkbox>
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周三" hide-details :value="3" required :rules="[rules.checkboxRules]"></v-checkbox>
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周四" hide-details :value="4" required :rules="[rules.checkboxRules]"></v-checkbox>
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周五" hide-details :value="5" required :rules="[rules.checkboxRules]"></v-checkbox>
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周六" hide-details :value="6" required :rules="[rules.checkboxRules]"></v-checkbox>
                    <v-checkbox v-model="weeks" dense class="mt-0 mr-4" label="周日" hide-details :value="0" required :rules="[rules.checkboxRules]"></v-checkbox>
                  </div>
                </div>
              </v-card>
            </v-col>
          </v-row>
        </v-form>
      </section>
    </template>
    <SearchProduct :show.sync="showSelectProduct" @selection="handleSelectProduct"></SearchProduct>
  </CustomTableCard>
</template>

<script>
import { mapMutations } from 'vuex'
import Calendar from "v-calendar/lib/components/calendar.umd";
import dayjs from "dayjs"
import * as planApi from '@/api/plan'
import SearchProduct from './components/select-product'
import mixin from './mixin'

export default {
  name: 'planSanpin',
  mixins: [mixin],
  components: {
    Calendar,
    SearchProduct
  },
  created() {
    this.cloneFormData()
    this.getList()
  },
  activated() {
    this.getList()
  },
  deactivated() {
    console.log('deactivated')
  },
  mounted() {

  },
  watch: {
    showSelectProduct(bool) {
      this.temporary = !bool
    }
  },
  data() {
    return {
      temporary: true,
      listLoading: false,
      page: 1,
      showDrawer: false,
      showSelectProduct: false,
      tableData: [{}],
      total: 0,
      queryParams: {
        page: 1,
        limit: 20,
        type: '',
        dateType: '',
        dateRange: [],
      },
      multipleSelection: [],
      dateRange: [],
      baseInfo: {
        id: undefined,
        foundation_prodcut_id: undefined,
        foundation_prodcut_name: '',
        plan_dateArr: [],
        day_num: '',
        remain_num: '',
        remain_status: 1
      },
      radioDateType: 1,
      selection: [],
      weeks: [],

      rules: {
        required: value => !!value || 'required',
        checkboxRules: value => !!value.length || 'required'
      },

      pickerOptions: {
        disabledDate(date) {
          date = dayjs(date)
          return date > dayjs().add(3, 'month') || date.diff(dayjs()) < 1
        }
      }
    }
  },

  methods: {
    dayjs,
    handleChangeType(a) {
      console.log(a)
    },
    // 克隆数据 用于重置数据使用
    cloneFormData() {
      this._baseInfo = Object.assign({}, this.baseInfo)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleMonthChange() {
      // console.log(1)
    },
    getList(page) {
      if (/\d+/.test(page)) {
        this.queryParams.page = page
      }
      this.listLoading = true
      planApi.getList(this.queryParams).then(response => {
        this.tableData = response.data.data
        this.total = response.data.count
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 编辑列表
    handleEdit(row) {
      this.showDrawer = true
      Object.assign(this.baseInfo, row)
    },
    // 删除列表
    handleRmove(row) {
      let ids = []
      if (row) {
        ids = [row.id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      this.$confirm(this.$t('tips.delete'), this.$t('other.tip'), {
        center: true,
        type: 'warning'
      }).then(() => {
        planApi.remove({idArr: ids}).then(() => {
          this.$message.success('success')
          this.getList()
        })
      })
    },
    // 批量设置状态
    setStatusAll(status) {
      let ids = this.multipleSelection.map(item => item.id)
      this.updateStatus({idArr: ids, status})
    },
    // 设置状态
    setStatus(row) {
      let status = row.status == 1 ? 2 : 1
      this.updateStatus({idArr: [row.id], status})
    },
    // 更新状态
    updateStatus(params) {
      planApi.setStatus(params).then(() => {
        this.$message.success('success')
        this.getList()
      })
    },
    gtToDay(day) {
      return dayjs(day.date).format('YYYY-MM-DD') > dayjs().format('YYYY-MM-DD')
    },
    isChecked(day) {
      let date = dayjs(day.date).format('YYYY-MM-DD')
      return this.selection.indexOf(date) > -1
    },
    setSelection(date) {
      let index = this.selection.indexOf(date)
      if (index > -1) {
        this.selection.splice(index, 1)
      } else {
        this.selection.push(date)
      }
    },
    handleClickDate(day) {
      if (dayjs(day.date).format('YYYY-MM-DD') > dayjs().format('YYYY-MM-DD') && this.radioDateType === 1) {
        this.setSelection(dayjs(day.date).format('YYYY-MM-DD'))
      }
    },
    handleSelectProduct(selection) {
      this.baseInfo.foundation_prodcut_id = selection.id
      this.baseInfo.foundation_prodcut_name = selection.name
    },
    handleRadioType(val) {
      if(val === 2) {
        this.selection = []
      }
    },
    // 右侧窗口关闭事件
    handleCancel() {
      this.resetForm()
    },
    // 重置表达数据和验证
    resetForm () {
      Object.assign(this.baseInfo, this._baseInfo)
      this.selection = []
      this.dateRange = []
      this.radioDateType = 1
      this.$refs.form.resetValidation()
    },
    // 右侧窗口确定事件
    handleOk() {
      if(!this.baseInfo.id) {
        if (this.radioDateType == 1) {
          if (!this.selection.length) {
            return this.$message.warning('请选择日期')
          }
          this.baseInfo.plan_dateArr = this.selection
        } else {
          if (!this.dateRange.length) {
            return this.$message.warning('请选择日期范围')
          }
          let [date1, date2] = [dayjs(this.dateRange[0]), dayjs(this.dateRange[1])]
          let day = date2.diff(date1, 'day')
          for(let i = 0; i <= day; i++) {
            let date = date1.add(i, 'day')
            if(this.weeks.indexOf(date.day()) > -1) {
              this.baseInfo.plan_dateArr.push(date.format('YYYY-MM-DD'))
            }
          }
        }
      }
      console.log(this.baseInfo)
      if(this.$refs.form.validate()) {
        if(this.baseInfo.id) {
          planApi.edit(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList()
            this.showDrawer = false
          })
        } else {
          planApi.adds(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList(1)
            this.showDrawer = false
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.calendar-body-gray {
  padding: 0 10px;
  outline: 1px solid #e1e1e1;
  color: #999;
  height: 80px;
  overflow: hidden;
  position: relative;
  background: #f1f1f1;
}
.calendar-body-item {
  padding: 0 10px;
  outline: 1px solid #e1e1e1;
  height: 80px;
  overflow: hidden;
  position: relative;
  background: #fff;
  z-index: 1;
}
.calendar-body-item.checked {
  /* outline: 1px solid #2d8cf0; */
  /* z-index: 2; */
  background: #eaf3fd;
}
.calendar-body-item.disable {
  background: #f1f1f1;
}
.calendar-body-item_date {
  font-size: 14px;
  font-weight: bold;
  padding: 10px 0;
}
</style>